﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebAPI.Filter
{
    public class ApiActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
        }

      

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);
            var request = actionContext.Request;
            string method = request.Method.Method;

            string userid = string.Empty;
            string controlerName = actionContext.ControllerContext.ControllerDescriptor.ControllerName;
            string actionName = actionContext.ActionDescriptor.ActionName;
            if (actionName.Equals("GetToken"))//指定控制器可以访问
            {

                
            }
            else
            {
                if (request.Headers.Contains("Token"))
                {
                    string tokenValue = request.Headers.GetValues("Token").FirstOrDefault();
                    if (!tokenValue.Equals("yfc"))
                    {
                        var requespose = new HttpResponseMessage();
                        requespose.Content = new StringContent("Tocken验证失败！");
                        requespose.StatusCode = System.Net.HttpStatusCode.MethodNotAllowed;
                        throw new HttpResponseException(requespose);
                    }
                }
                else {
                    var requespose = new HttpResponseMessage();
                    requespose.Content = new StringContent("Tocken数据错误！");
                    requespose.StatusCode = System.Net.HttpStatusCode.MethodNotAllowed;
                    throw new HttpResponseException(requespose);
                }
               
            }
        }
    }
}